// const redis = require('../utils/redis')
const log4js = require('../utils/log4')
const logger = log4js.getLogger('middleware/authenticate.js')

/** 鉴权中间件 */
const authenticate = async (req, res, next) => {
  try {
    // 从请求头中获取 token
    
    const session = req.headers.session

    if (!session) {
      return res.status(401).json({ status: 1, message: 'Unauthorized - Token not provided' })
    }

    // 验证 session
    const adminId = await redis.get(`session:sessionId:${session}`)
    const sessionId = await redis.get(`session:adminId:${adminId}`)

    if (adminId === null || sessionId === null || sessionId !== session) {
      return res.status(401).json({ status: 1, message: 'Unauthorized - Invalid token' })
    }

    const decoded = { id: Number(adminId) }

    // 将解码后的用户信息添加到请求对象中
    console.log(decoded)
    req.user = decoded

    next()
  } catch (error) {
    logger.error(error)
    return res.status(401).json({ status: 1, message: 'Unauthorized - Invalid token' })
  }
}

module.exports = authenticate
